/**
 * create by young (young2f@outlook.com) on 2020/12/4
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const moment = require('moment');
const table = 'Customer';
module.exports = class extends base {
  async findMany(body) {
    const { ctx, service } = this;

    const { table, customer, salesman, company, tenantCode } = body;
    delete body['table'];

    if (table === 'DicExperiment') {
      if (customer) body['customer'] = { $regex: customer };
      if (salesman) body['salesman'] = { $regex: salesman };
      if (company) body['company'] = { $regex: company };
      const result = await ctx.app.dbs.find(table, body);
      return { status: 'ok', result };
    }
    if (table === 'DicReimburse') {
      const query = { tenantCode };
      const { records = [] } = body;
      delete body['tenantName'];
      delete body['tenantCode'];
      delete body['records'];

      const schema = await service.globalService.getModel({ table });
      _.map(body, (value, key) => {
        const temp = _.find(schema, (it, k) => {
          return k === key;
        });

        if (temp) {
          const { _type } = temp;
          query[key] = this.getValue(_type, value, key);
        }
      });

      _.map(records, (value, key) => {
        const temp = _.find(schema.records.cols, it => {
          return it.key === key;
        });

        if (temp) {
          const { _type } = temp;
          const _key = `records.${key}`;
          query[_key] = this.getValue(_type, value, _key);
        }
      });

      const { key } = body;
      const _key = key ? key : 'createdTs';

      const sort = {};
      sort[_key] = -1;

      console.log('queryy', query);
      const result = await ctx.app.dbs.aggregate(table, [
        { $match: { ...query } },
        { $sort: { ...sort } },
      ]);

      return { status: 'ok', result };
    }
    const result = await ctx.app.dbs.find(table, body);
    return { status: 'ok', result };
  }

};
